<template>
    <div class="rules_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="expandHandle" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button v-auth="'CREATE_RULE'" type="primary" @click="createRules">创建规则</el-button>
            </template>
        </ZwTable>
    </div>
    <ZWDrawer ref="DrawerRef" @close="handleClose">
        <ZwSearchForm row-num="3" :option="searchOption2" @search="search2" @reset="reset2" @expand="getTableH" />
        <ZwTable
            ref="tableRef2"
            class="table-box"
            :option="tableOption2"
            :fetch-params="state2.searchParams"
            :fetch-api="fetchApi2()">
        </ZwTable>
    </ZWDrawer>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="del" />
</template>

<script setup lang="tsx">
import { reactive, ref, onMounted, computed } from 'vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { deepCopy } from '@/utils/helper';
import { ElTag, ElButton, ElMessage, ElPopover, ElAvatar } from 'element-plus';

import { ruleList, ruleStatus, delRule, ruleDetaile } from '@/api/rules';
import dialogSearch from './components/dialogSearch.vue';
import ZWDrawer from '@/components/ZWDrawer.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import { store } from '@/store';
import router from '@/router';
import { getSetionId, tableH, reSize } from '@/utils/utils';
import { customerSource } from '@/api/rules';
import male from '@/assets/chatDetails/male.png';
import female from '@/assets/chatDetails/female.png';

const DrawerRef = ref(null);
const DeletdialogRef = ref(null);
const selfSelectId = ref(); //所选id
const cust_tag_rule_id = ref();
const tableData = ref([]);
const dialogData = ref([]);
const tableRef = ref();
const tableRef2 = ref();
const sourceList = ref([]);
const page = reactive({
    page: 1,
    page_size: 15
});
const dialogPage = reactive({
    page: 1,
    page_size: 15
});
const form = reactive({
    title: '',
    rule_status: 0,
    create_uids: [],
    create_time: []
});
const dialogForm = reactive({
    cust_resource: '',
    effective_employee_ids: [],
    label_time: '',
    name: '',
    mobile: ''
});
const defaultParams = reactive({
    title: '',
    create_time: [],
    rule_status: 0
});
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '规则名称',
            name: 'title',
            value: '',
            type: 'input',
            placeholder: '请输入规则名称'
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        },
        {
            label: '状态',
            name: 'rule_status',
            value: '',
            type: 'select',
            placeholder: '请选择状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        {
                            id: 0,
                            name: '全部'
                        },
                        {
                            id: 1,
                            name: '未开始'
                        },
                        {
                            id: 2,
                            name: '进行中'
                        },
                        {
                            id: 3,
                            name: '已结束'
                        },
                        {
                            id: 4,
                            name: '已暂停'
                        }
                    ]);
                });
            },
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const searchOption2 = computed(() => {
    return [
        {
            label: '客户来源',
            name: 'cust_resource',
            value: [],
            type: 'select',
            placeholder: '请选择客户来源',
            multiple: true,
            collapseTags: true,
            filterable: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    customerSource({ page: 1, page_size: 99999 }).then((r: any) => {
                        r.data = r.data || [];
                        resolve(r.data);
                    });
                });
            }
        },
        {
            label: '归属员工',
            name: 'effective_employee_ids',
            value: [],
            type: 'select',
            placeholder: '请选择归属员工',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '打标时间',
            name: 'label_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        },
        {
            label: '客户名称',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入客户名称'
        },
        {
            label: '客户手机',
            name: 'mobile',
            value: '',
            type: 'input',
            placeholder: '请输入客户手机号'
        }
    ];
});
const tableOption = [
    {
        prop: 'title',
        label: '标签规则名称',
        minWidth: 150
    },
    {
        prop: 'cust_tag_list',
        label: '自动打标签',
        minWidth: 400,
        isTag: true
    },
    {
        prop: 'validity_type',
        label: '有效期',
        width: 320,
        render({ row }) {
            return <span> {row.validity_type == 1 ? '永久有效' : row.start_time + ' 至 ' + row.end_time}</span>;
        }
    },
    {
        prop: 'current_cust_count',
        label: '当前客户数',
        width: 100
    },
    {
        prop: 'new_today_count',
        label: '今日新增/减少客户数',
        width: 160,
        render({ row }) {
            return <span>{row.new_today_count + '/' + row.reduce_cust_count}</span>;
        }
    },
    {
        prop: 'status_name',
        label: '状态',
        width: 100
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180
    },
    {
        prop: 'updated_at',
        label: '最近修改时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 200,
        isOperate: true,
        option: [
            {
                name: '编辑',
                authCode: 'EDIT',
                click: (row: any) => {
                    editItem(row.id);
                }
            },
            {
                name: '开启',
                authCode: 'OPEN_PAUSE',
                click: (row: any) => {
                    openClose(row);
                },
                isRender: ({ row }: any) => !['已结束', '未开始'].includes(row.status_name) && row.status == 2
            },
            {
                name: '暂停',
                authCode: 'OPEN_PAUSE',
                click: (row: any) => {
                    openClose(row);
                },
                isRender: ({ row }: any) => !['已结束', '未开始'].includes(row.status_name) && row.status != 2
            },
            {
                name: '客户明细',
                authCode: 'VIEW_CUSTOMER_DETAIL',
                click: (row: any) => {
                    getDetail(row);
                }
            }
        ]
    }
];
const tableOption2 = [
    {
        prop: 'cust_avatar',
        label: '客户信息',
        width: 300,
        render({ row }) {
            return (
                <div style="display: flex; align-items: center">
                    <ElAvatar shape="square" size={36} src={row.avatar} />
                    <span style="margin-left: 12px">{row.name || '--'}</span>
                    <span style="margin-right: 6px"> {row.mobile ? '(' + row.mobile + ')' : '手机号暂无'}</span>
                    <img src={male} vShow={row.sex === 1} />
                    <img src={female} vShow={row.sex === 2} />
                </div>
            );
        }
    },
    {
        prop: 'effective_employee_name',
        label: '归属员工',
        popperClass: 'zw-hide_select_option',
        render({ row }) {
            return <div>{row.effective_employee_name || '--'}</div>;
        }
    },
    {
        prop: 'cust_resource',
        label: '客户来源'
    },
    {
        prop: 'created_at',
        label: '打标时间'
    }
];
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return ruleList;
};
const search = (data: any) => {
    state.searchParams = deepCopy(data);
};
const reset = (v: any) => {
    state.searchParams = deepCopy(defaultParams);
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

const tabH = ref('400px');
// 表格的自适应高度
const getTableH = () => {
    tabH.value = tableH('.table-box');
};
//获取标签规则列表
const callBackFunc = () => {
    const params = {
        ...page,
        ...form
    };
    ruleList(params).then((res: any) => {
        tableData.value = res.data;
        store.dispatch('pageTotal', res.total);
    });
};

const getRowKey = (row: any) => {
    return row.id;
};

const defaultParams2 = reactive({
    cust_tag_rule_id: '',
    cust_resource: '',
    effective_employee_ids: [],
    label_time: [],
    name: '',
    mobile: ''
});
const state2 = reactive({
    searchParams: deepCopy({ ...defaultParams2, cust_tag_rule_id: cust_tag_rule_id.value })
});
const search2 = (data: any) => {
    const res = { ...defaultParams2, ...data, cust_tag_rule_id: cust_tag_rule_id.value };
    state2.searchParams = res;
};
const reset2 = (v?: any) => {
    const res = { ...defaultParams2, ...v, cust_tag_rule_id: cust_tag_rule_id.value };
    state2.searchParams = res;
};
const fetchApi2 = () => {
    // 获取文件列表
    // getTableH()
    return ruleDetaile;
};

//获取标签规则明细
const getSource = () => {
    const params = {
        cust_tag_rule_id: cust_tag_rule_id.value,
        ...dialogForm,
        ...dialogPage
    };
    ruleDetaile(params).then((res: any) => {
        dialogData.value = res.data;
        store.dispatch('pageTotal', res.total);
    });
};
//创建规则
const createRules = () => {
    router.push({ path: '/customer/tag/rules/addRules' });
};
//查看明细
const getDetail = (val: any) => {
    DrawerRef.value.title = `【${val.title}】客户明细`;
    DrawerRef.value.width = 1000;
    DrawerRef.value.isShow = false;
    cust_tag_rule_id.value = val.id;
    state2.searchParams.cust_tag_rule_id = val.id;
    DrawerRef.value.drawer = true;

    dialogPage.page = 1;
    dialogPage.limit = 15;
};
//编辑
const editItem = (val: any) => {
    router.push({
        path: '/customer/tag/rules/addRules',
        query: {
            custId: val,
            type: 'edit'
        }
    });
};
//开启、暂停
const openClose = (val: any) => {
    const params = {
        cust_rule_tag_id: val.id,
        status: val.status == 2 ? 1 : 2
    };
    ruleStatus(params).then((res: any) => {
        ElMessage.success(val.status == 2 ? '开启成功！' : '暂停成功！');
        tableRef.value.reload();
    });
};
//删除
const remove = (val: any) => {
    selfSelectId.value = val;
    DeletdialogRef.value.appDialog.visible = true;
};
//确认删除
const del = () => {
    delRule({
        cust_rule_tag_id: selfSelectId.value
    }).then((res: any) => {
        ElMessage.success(`删除成功`);
        DeletdialogRef.value.appDialog.visible = false;
        tableRef.value.reload();
    });
};
const getPagination = (res: any) => {
    page.page = res.page;
    page.limit = res.page_size;
    callBackFunc();
};
const dialogParams = (res: any) => {
    dialogForm.cust_resource = res.cust_resource;
    dialogForm.effective_employee_ids = res.effective_employee_ids;
    dialogForm.label_time = res.label_time;
    dialogForm.name = res.name;
    dialogForm.mobile = res.mobile;
    getSource();
};
const initPagination = (res: any) => {
    dialogPage.page = res.page;
    dialogPage.limit = res.page_size;
    getSource();
};
const handleClose = () => {
    callBackFunc();
};
onMounted(() => {
    getTableH();
    reSize(getTableH);
});
</script>
<style lang="scss" scoped>
.rules_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}
</style>
